package com.nicefact.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.nicefact.core.AppException;

public class CommonUtil {

	//private static final AppLogger log = AppLogger.getLogger(GoogleConversionService.class);

	public static void dispatchRequest(HttpServletRequest request, HttpServletResponse response, String path)
			throws AppException {
		try {
			RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
			requestDispatcher.forward(request, response);
			// response.sendRedirect(path);
		} catch (IOException ioException) {
			throw new AppException("Unable to redirect to " + path, ioException);
		} catch (ServletException servletException) {
			throw new AppException("Unable to dispatch redirect to " + path, servletException);
		}
	}

	public static String getCurrentUrl(String path) {
		String hostUrl = null;
		String environment = System.getProperty("com.google.appengine.runtime.environment");
		if (StringUtils.equals("Production", environment)) {
			String applicationId = System.getProperty("com.google.appengine.application.id");
			String version = System.getProperty("com.google.appengine.application.version");
			hostUrl = "http://" + applicationId + ".appspot.com/";
		} else {
			hostUrl = "";
		}
		return hostUrl + path;

	}

	public static String getImageUrl(String blobKeyString) {
		String imageUrl = null;
		String environment = System.getProperty("com.google.appengine.runtime.environment");
		if (StringUtils.equals("Production", environment)) {
			if (blobKeyString != null) {
				imageUrl = getCurrentUrl("resource/showImage.do?blobKey=" + blobKeyString);
			} else {
				imageUrl = getCurrentUrl("sample.png");
			}
		} else {
			imageUrl = getCurrentUrl("sample.png");
		}
		return imageUrl;

	}

	public static byte[] getByteArray(InputStream is) {

		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		try {
			int nRead;
			byte[] data = new byte[16384];
			while ((nRead = is.read(data, 0, data.length)) != -1) {
				buffer.write(data, 0, nRead);
			}

			buffer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return buffer.toByteArray();
	}

	public static byte[] getByteArrayfromUrl(String url) throws AppException {
		byte[] data = null;

		try {
			data = IOUtils.toByteArray(new URL(url).openStream());
		} catch (MalformedURLException e) {
			System.out.println("Unable to get data from url " + url);
			e.printStackTrace();
		} catch (IOException e) {
			// throw new AppException("Unable to get data from url "+url,e);
			System.out.println("Unable to get data from url " + url);
			e.printStackTrace();
		}
		return data;
	}

	public static byte[] getByteArrayfromDisk(String url) throws AppException {

		byte[] data = null;
		InputStream fileInputStream = PropertyUtil.class.getClassLoader().getResourceAsStream(url);
		if (fileInputStream != null) {
			// throw new AppException("Cannod read from  file with path "+url);
			data = getByteArray(fileInputStream);
		}

		return data;
	}

	public static <E> List<List<E>> getBuckets(List<E> entities, int batchSize) {
		int totalRecords = entities.size();
		int fromIndex = 0;
		List<List<E>> results = new ArrayList<List<E>>();
		while (totalRecords > 0) {
			if (totalRecords < batchSize) {
				batchSize = totalRecords;
				totalRecords = -1;
			}
			List<E> subList = new ArrayList<E>();
			subList = getSubList(entities, fromIndex, (fromIndex + batchSize));
			if (!(subList.isEmpty())) {
				results.add(subList);
			}
			totalRecords = totalRecords - batchSize;
			fromIndex = fromIndex + batchSize;
		}
		return results;
	}

	private static <E> List<E> getSubList(List<E> enities, int fromIndex, int toIndex) {
		List<E> subList = new ArrayList<E>();
		if ((enities != null) && !(enities.isEmpty())) {
			for (int i = fromIndex; i < toIndex; i++) {
				subList.add(enities.get(i));
			}
		}
		return subList;
	}

	public static HttpSession getCurrentSession() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession(false);
	}


}
